package quartz.config;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

@Slf4j
// @Configuration(proxyBeanMethods = false)
class QuartzConfig {
    @Bean
    SchedulerFactoryBeanCustomizer schedulerFactoryBeanCustomizer(JdbcTemplate jdbcTemplate) {
        return schedulerFactoryBean -> { // 注册全局监听器
            schedulerFactoryBean.setGlobalJobListeners(new JobListener() {
                final String SQL = "INSERT INTO QRTZ_JOB_HISTORY(job_name, trigger_time, duration, status, error) VALUES(?, ?, ?, ?, ?)";

                @Override
                public String getName() {
                    return "QRTZ_JOB_HISTORY";
                }

                @Override
                public void jobToBeExecuted(JobExecutionContext context) {
                }

                @Override
                public void jobExecutionVetoed(JobExecutionContext context) {
                }

                @Override
                public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
                    try {
                        JobDetail job = context.getJobDetail();
                        Trigger trigger = context.getTrigger();
                        long duration = context.getJobRunTime();
                        String status = jobException == null ? "SUCCESS" : "FAILED";
                        String error = jobException == null ? null : jobException.getMessage();
                        jdbcTemplate.update(SQL, job.getKey().getName(), trigger.getStartTime(), duration, status, error);
                    } catch (Exception e) {
                        log.error("QRTZ_JOB_HISTORY", e);
                    }
                }
            });
        };
    }
}